#pragma once

#include <iostream>
#include <poll.h>
#include <sys/time.h>
#include <string>
#include "Socket.hpp"

static const int fd_num_max = 64;
int defaultfd = -1;
int no_event = 0;

class PollServer
{
public:
    PollServer(uint16_t port) : m_port(port)
    {
        for (int i = 0; i < fd_num_max; ++i)
        {
            m_event_fds[i].fd = defaultfd;
            m_event_fds[i].events = no_event;
            m_event_fds[i].revents = no_event;
        }
    }
    ~PollServer()
    {
        m_listenSock.Close();
    }

    void init()
    {
        m_listenSock.Socket();
        m_listenSock.Bind(m_port);
        m_listenSock.Listen();
        log(INFO, "init SelectServer success ...");
    }

    void start()
    {
        int listenSock = m_listenSock.Fd();
        m_event_fds[0].fd = listenSock;
        m_event_fds[0].events = POLLIN;  // 用户告诉内核关心该套接字的读就绪
        int timeout = 1000;
        while (true)
        {
            int n = poll(m_event_fds, fd_num_max, timeout);
            switch (n)
            {
            case 0:
                std::cout << "time out ..." << std::endl;
                break;
            case -1:
                std::cerr << "poll error " << std::endl;
                break;
            default:
                // 有事件就绪了
                std::cout << "get a new link!!!" << std::endl; 
                Dispatcher();                            // 就绪的事件和fd你怎么知道只有一个呢？
                break;
            }
            // sleep(1);
        }
    }

    void Accepter()
    {
        // 我们的连接事件就绪
        std::string clientip;
        uint16_t clientport;
        int newfd = m_listenSock.Accept(&clientip, &clientport); // 会不会阻塞在这里?不会
        if (newfd < 0)
        {
            return;
            // continue;
        }
        log(INFO, "accept success,[%s: %d], newfd: %d", clientip.c_str(), clientport, newfd);

        int pos = 1;
        for (; pos < fd_num_max; ++pos) // 第二个循环
        {
            if (m_event_fds[pos].fd != defaultfd)
                continue;
            else
                break;
        }
        if (pos == fd_num_max)
        {
            // 数组已满
            log(WARNING, "server is full, close %d now!", newfd);
            close(newfd);

            // 可以扩容
        }
        else
        {
            m_event_fds[pos].fd = newfd;
            m_event_fds[pos].events = POLLIN;
            // TODO
            PrintFd();
        }
    }
    void Recver(int fd, int pos)
    {
        // 其他文件描述符读事件就绪
        char buffer[1024];
        ssize_t n = read(fd, buffer, sizeof(buffer) - 1);
        if (n > 0)
        {
            buffer[n] = 0;
            std::cout << "get a message: " << buffer << std::endl;
        }
        else if (n == 0)
        {
            log(INFO, "client quit, me too, close fd is: %d", fd);
            close(fd);
            m_event_fds[pos].fd = defaultfd; // 这里本质是从select中移除
        }
        else
        {
            // todo
        }
    }

    void Dispatcher()
    {
        for (int i = 0; i < fd_num_max; i++) // 第三次循环
        {
            int fd = m_event_fds[i].fd;
            if (fd == defaultfd)
                continue;
            if (m_event_fds[i].revents & POLLIN)
            {
                // 把所有的就绪事件派发给不同的模块
                if (fd == m_listenSock.Fd())
                {
                    Accepter();  // 连接管理器
                }
                else // 不是listen套接字就绪
                {
                    Recver(fd, i);   // 
                }
            }
        }
    }

    void PrintFd()
    {
        std::cout << "online fd list: ";
        for (int i = 0; i < fd_num_max; ++i)
        {
            if (m_event_fds[i].fd == defaultfd)
                continue;
            else
            {
                std::cout << m_event_fds[i].fd << " ";
            }
        }
        std::cout << std::endl;
    }

private:
    Sock m_listenSock;
    uint16_t m_port;
    struct pollfd m_event_fds[fd_num_max];

};